package com.raft.framework.vo

import android.text.TextUtils
import com.raft.framework.api.BaseResult


data class Resource<out T>(val status: Status,
                           val data: T?,
                           val message: String?,
                           private val isFirst:Boolean = false,
                           val payload:Any?=null,
                           val errorCode:Int = 0) {
    companion object {
        fun <T> success(data: T?,isFirst: Boolean = false,payload:Any?=null): Resource<T> {
            return Resource(Status.SUCCESS, data, null,isFirst,payload)
        }

        fun <T> error(msg: String?, data: T?=null,isFirst:Boolean = false): Resource<T> {
            return Resource(Status.ERROR, data, msg,isFirst)
        }

        fun <T> error(baseResult: BaseResult<*>?, isFirst:Boolean = false):Resource<T>{
            if(baseResult!=null && !TextUtils.isEmpty(baseResult.msg)){
                return Resource(Status.ERROR, null, baseResult.msg,isFirst = isFirst, errorCode = baseResult.statusCode)
            }
            return error("error",isFirst = isFirst)
        }

        fun <T> loading(data: T?=null): Resource<T> {
            return Resource(Status.LOADING, data, null)
        }
    }

    fun isOk() = status == Status.SUCCESS

    fun inLoading() = status == Status.LOADING

    fun hasError() = status == Status.ERROR

    fun haveData() = data != null

    fun isFirst() = isFirst
}

enum class Status {
    SUCCESS,
    ERROR,
    LOADING
}